package com.xxx.yuedong.community.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xxx.yuedong.common.R;
import com.xxx.yuedong.community.controller.form.ActivityAddNewForm;
import com.xxx.yuedong.community.pojo.Activity;
import com.xxx.yuedong.community.service.ActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

@Api(tags = "活动")
@RestController
@RequestMapping("/activity")
@Slf4j
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @PostMapping("/add-new")
    @ApiOperation("发布活动")
    @ApiOperationSupport(order = 100)
    public R insert(@Valid @RequestBody ActivityAddNewForm form) {
        log.debug("开始处理 【发布活动】 参数{}", form.toString());
        Activity activity = JSONUtil.parse(form).toBean(Activity.class);
        activity.setUserId(StpUtil.getLoginIdAsLong());
        // 加入活动人员，发布活动时，发布人即是活动人员
        ArrayList<Long> members = new ArrayList<>();
        members.add(StpUtil.getLoginIdAsLong());
        activity.setMembers(members.toString());
        activity.setCreateTime(new Date());

        int rows = activityService.insert(activity);
        R r = new R();
        r.put("rows",rows);
        r.put("activity", activity);
        return r;
    }

    @PostMapping("/{id:[0-9]+}/delete")
    @ApiOperation(value = "删除活动")
    @ApiOperationSupport(order = 200)
    public R delete(@PathVariable Long id) {
        log.debug("开始处理 【删除活动】 参数{}", id);
        int rows = activityService.deleteById(id);
        return R.ok().put("rows",rows);
    }

    @PostMapping("/{id:[0-9]+}/addActivityById")
    @ApiOperation(value = "加入活动")
    @ApiOperationSupport(order = 300)
    public R addActivityById(@PathVariable Long id) {
        log.debug("开始处理 【加入活动】");
        int rows = activityService.addActivityById(id);
        return R.ok().put("rows",rows);
    }

    @PostMapping("/{id:[0-9]+}/checkActivity")
    @ApiOperation(value = "签到活动")
    @ApiOperationSupport(order = 400)
    public R checkActivity(@PathVariable Long id) {
        log.debug("开始处理 【签到活动】");
        int rows = activityService.checkActivity(id);
        return R.ok().put("rows",rows);
    }

    @PostMapping("")
    @ApiOperation(value = "查询所有活动")
    @ApiOperationSupport(order = 500)
    public R searchAllActivity() {
        log.debug("开始处理 【查询所有活动】");
        ArrayList<HashMap> activityList = activityService.searchAllActivity();
        return R.ok().put("activities",activityList);
    }

}
